import requests
from concurrent.futures import ThreadPoolExecutor

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
    'Referer': 'https://movie.douban.com/explore',
}
# url = 'https://m.douban.com/rexxar/api/v2/movie/recommend?refresh=0&start=0&count=20&selected_categories=%7B%7D&uncollect=false&tags='
url = 'https://m.douban.com/rexxar/api/v2/movie/recommend?'

params = {
    'count': '20',
    'tags': '灾难'
}

try:
    res = requests.get(url, headers=headers, params=params)
    items = res.json()['items']
except requests.exceptions.RequestException as e:
    print(f"Error occurred while fetching data: {e}")
    exit(1)


def download_image(title, url):
    try:
        res = requests.get(url, headers=headers)
        with open(f'./img/{title}.jpg', 'wb') as f:
            f.write(res.content)
        print(title, '下载完成！')
    except requests.exceptions.RequestException as e:
        print(f"Error occurred while downloading image for {title}: {e}")


if __name__ == '__main__':
    with ThreadPoolExecutor() as executor:
        for m in items:
            if "title" in m and "pic" in m:
                title_name = m["title"]
                executor.submit(download_image, title_name, m['pic']['large'])
            else:
                print("该项没有标题或图片")
